package com.skywolf.chem.live.controller;


import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.skywolf.chem.common.sysconfig.pojo.dto.PageDTO;
import com.skywolf.chem.common.sysconfig.pojo.vo.PageVO;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.customer.entity.Signup;
import com.skywolf.chem.customer.service.ISignupService;
import com.skywolf.chem.live.entity.Live;
import com.skywolf.chem.live.param.LiveDto;
import com.skywolf.chem.live.param.LiveParam;
import com.skywolf.chem.live.param.VideoDto;
import com.skywolf.chem.live.service.ILiveService;
import com.skywolf.chem.tencent.FileController;
import com.skywolf.chem.tencent.service.ImService;
import com.skywolf.chem.tencent.service.LiveInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 直播信息表 前端控制器
 * </p>
 *
 * @author 
 * @since 2020-11-30
 */
@RestController
@RequestMapping("/edu/live")
@Api(value = "API-直播相关接口", description = "API-直播相关接口")
public class LiveController {
    Logger logger = LoggerFactory.getLogger(LiveController.class);

    @Autowired
    ILiveService liveService;

    @Autowired
    ImService imService;

    @Autowired
    ISignupService signupService;

    @Autowired
    LiveInfoService liveInfoService;

    @ApiOperation(value = "腾讯云直播录制回调",notes = "腾讯云直播录制回调")
    @RequestMapping(value = "/liveback",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Integer>> liveback(HttpServletRequest request, @RequestBody Map<String, Object> mediaMap) {
        // 应答：HTTP STATUS CODE = 200，服务端忽略应答包具体内容，为了协议友好，建议应答内容携带 JSON： {"code":0} 通知可靠性
        logger.info("liveback data:"+ JSON.toJSONString(mediaMap));
        Map<String, Integer> responseMap = new HashMap<>(16);
        responseMap.put("code", 0);
//        String eventType = mediaMap.get("event_type").toString();
        // 如果非录制文件消息就不处理
//        if (!"100".equals(eventType)) {
//            return new ResponseEntity<Map<String, Integer>>(responseMap, HttpStatus.OK);
//        }
        try{
            String timetableId = mediaMap.get("stream_id").toString();
            String videoUrl = mediaMap.get("video_url").toString();
            String duration = mediaMap.get("duration").toString();
            String file_size = mediaMap.get("file_size").toString();

            Live live = new Live();
            live.setBackUrl(videoUrl);
            live.setDuration(duration);
            live.setFileSize(file_size);
            live.setId(Long.valueOf(timetableId));
            live.setPlayStatus(1);
            liveService.updateById(live);

            Signup signup = new Signup();
            signup.setStudy(1);
            signupService.update(signup,
                new UpdateWrapper<Signup>().eq("live_id",live.getId()));
            return new ResponseEntity<>(responseMap, HttpStatus.OK);
        }catch (Exception e){
            logger.error("liveback data:"+ JSON.toJSONString(mediaMap)+"error:{}",e);
        }
        return new ResponseEntity<>(responseMap, HttpStatus.FAILED_DEPENDENCY);
    }

    @ApiOperation(value = "获取群组id",notes = "获取群组id")
    @RequestMapping(value = "/liveGroupId",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> liveGroupId(HttpServletRequest request,@RequestParam(value = "liveId",required = true) Long liveId) {
        Live live = liveService.getById(liveId);
        if(live==null){
            return RespData.failResult("直播间不存在!");
        }else{
            try{
                if(StringUtils.isNotBlank(live.getGroupId())){
                    return RespData.success(live.getGroupId());
                }
                String sig = imService.getGroupId(liveId+"");
                Live model = new Live();
                model.setId(live.getId());
                model.setGroupId(sig);
                if(StringUtils.isNotBlank(sig)){
                    liveService.updateById(model);
                }
                return RespData.success(sig);
            }catch (ServiceException e){
                return RespData.success(e.getErrorMessage());
            }
        }
    }

    @ApiOperation(value = "首页-直播报名列表",notes = "首页-直播报名列表")
    @RequestMapping(value = "/liveList",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PageVO<VideoDto>> liveList(HttpServletRequest request, @RequestBody @Validated PageDTO queryParam) {
        PageVO<VideoDto> page = liveService.pageLiveList(queryParam);
        return RespData.success(page);
    }

    @ApiOperation(value = "直播列表-报名直播",notes = "直播列表-报名直播")
    @RequestMapping(value = "/enrollLive",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> enrollLive(HttpServletRequest request, @RequestBody @Validated LiveParam param) {
        String uid = request.getHeader("uid");
        try{
            liveService.enrollLive(param,Long.valueOf(uid));
            return RespData.success("success");
        }catch (ServiceException e){
            return RespData.failResult(e.getErrorMessage());
        }
    }

    @ApiOperation(value = "正在直播列表",notes = "正在直播列表")
    @RequestMapping(value = "/liveUser",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PageVO<VideoDto>> liveUser(HttpServletRequest request, @RequestBody @Validated PageDTO queryParam) {
        String uid = request.getHeader("uid");
        PageVO<VideoDto> page = liveService.liveUser(queryParam,Long.valueOf(uid));
        return RespData.success(page);
    }

    @ApiOperation(value = "直播时调用-直播所有信息",notes = "直播时调用-直播所有信息")
    @RequestMapping(value = "/viewLive",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<LiveDto> viewLive(HttpServletRequest request, @RequestParam(value = "liveId",required = true) Long liveId) {
        String uid = request.getHeader("uid");
        LiveDto live = liveService.getLiveInfo(liveId,Long.valueOf(uid));
        if(live==null){
            return RespData.failResult("直播不存在或未报名！");
        }
        if(live.getStatus()==0){
            return RespData.failResult("该直播已下架！");
        }
        if(live.getBmStatus()!=1){
            return RespData.failResult("直播报名未通过！");
        }
        if(StringUtils.isBlank(live.getPullFlow())){
            return RespData.failResult("直播还未开始！");
        }
//        Signup signup = new Signup();
//        signup.setStudy(1);
//        signupService.update(signup,
//                new UpdateWrapper<Signup>().eq("user_id", Long.valueOf(uid)).eq("live_id",liveId));
        return RespData.success(live);
    }

    @ApiOperation(value = "报名直播详情",notes = "报名直播详情")
    @RequestMapping(value = "/getLiveInfo",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<LiveDto> getLiveInfo(HttpServletRequest request, @RequestParam(value = "liveId",required = true) Long liveId) {
        Live live = liveService.getById(liveId);
        if(live==null){
            return RespData.failResult("直播不存在！");
        }
        LiveDto dto = new LiveDto();
        BeanUtils.copyProperties(live,dto);
        QueryWrapper<Signup> queryWrapper=new QueryWrapper();
        queryWrapper.eq("live_id",Long.valueOf(liveId));
        Integer bmCount = signupService.count(queryWrapper);
        dto.setBmCount(bmCount);
        if(live.getSignTime()==null){
            dto.setStatusStr("报名未开始");
        }else{
            if(System.currentTimeMillis() < Instant.from(live.getSignTime().atZone(ZoneId.systemDefault())).toEpochMilli()){
                dto.setStatusStr("报名未开始");
            }else if(System.currentTimeMillis() >= Instant.from(live.getEndTime().atZone(ZoneId.systemDefault())).toEpochMilli()){
                dto.setStatusStr("报名结束");
            }else{
                dto.setStatusStr("报名中");
            }
        }
        return RespData.success(dto);
    }

    @ApiOperation(value = "直播观看人数",notes = "直播观看人数")
    @RequestMapping(value = "/liveUserCount",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PageVO<VideoDto>> liveUserCount(HttpServletRequest request, @RequestParam(value = "liveId",required = true) Long liveId) {
        Long count = liveInfoService.getGroupUserCount(liveId);
        return RespData.success(count);
    }

}
